<?php

namespace ZhaohangYang\ToolsPhpYimi;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

class YimiBasic
{
    // 易米请求接口数据，需要的
    public static $yimiParams;
    public static $client;

    // 易米云通初始化
    public static function init($yimi_config = [])
    {
        self::$yimiParams = $yimi_config;
    }

    // 返回实例化的请求客户端
    public static function getClient()
    {
        if (!(self::$client instanceof Client)) {

            $basic_url = self::$yimiParams['is_test'] ? 'http://apiusertest.emic.com.cn' : 'http://api.emic.com.cn';
            $headers   = [];
            // 初始化请求易米的客户端
            self::$client = new Client(['base_uri' => $basic_url, 'headers' => $headers]);
        }
        return self::$client;
    }

    // 获取请求证书
    public static function sigParameter()
    {
        $time = date('YmdHis', $_SERVER['REQUEST_TIME']);
        return strtoupper(MD5(self::$yimiParams['sub_account_sid'] . self::$yimiParams['sub_auth_token'] . $time));
    }

    // 获取请求授权
    public static function authorization()
    {
        $time = date('YmdHis', $_SERVER['REQUEST_TIME']);
        return base64_encode(self::$yimiParams['sub_account_sid'] . ':' . $time);
    }

    // 获取请求授权
    public static function getPreHeaders($body)
    {
        return [
            'Accept'         => 'application/json',
            'Content-Type'   => 'application/json;charset=utf-8',
            'Authorization'  => self::authorization(),
            // Http 净荷数据长度，根据实际 xml 或 json 内容长度填写
            'Content-Length' => strlen($body),
        ];
    }

    // 发送易米请求
    public static function sendResquest($url, $body)
    {
        $body    = json_encode($body);
        $headers = self::getPreHeaders($body);

        $request  = new Request('POST', $url, $headers, $body);
        $response = self::getClient()->send($request, ['timeout' => 10]);

        return json_decode($response->getBody(), true);
    }
}
